import type { AxiosResponse } from 'axios';

import { baseRequestClient } from '#/api/request';

// baseRequestClient和requestClient都是axios的实例
// 区别在于请求和响应拦截器的设置不一样
// baseRequestClient是使用默认请求和响应拦截
// requestClient集成了多个拦截器：authenticateResponseInterceptor、errorMessageResponseInterceptor
// 授权相关：authenticateResponseInterceptor
// 错误统一管理：errorMessageResponseInterceptor
// 更改响应结构：
import { requestClient } from '../request';
// env文件中的环境变量在开发环境下 可以通过import.meta.env访问
// 生成环境通过window._VBEN_ADMIN_PRO_APP_CONF_访问
// console.log('import.meta.env', import.meta.env);

export namespace AuthApi {
  export interface RegisterParams {
    username: string;
    password: string;
    uuid: string;
    code: string;
  }
  export interface RegisterResult {
    code: number;
    msg: string;
  }
  export interface GetCaptchaImageResult {
    msg: string;
    img: string;
    code: number;
    captchaOnOff: boolean;
    uuid: string;
  }

  // 登录接口参数
  export interface LoginParams {
    password?: string;
    username?: string;
  }
  // 登录接口返回值
  export interface LoginResult {
    accessToken: string;
  }

  export interface RefreshTokenResult {
    data: string;
    status: number;
  }
}

// 获取验证码
// 返回值:Promise<AuthApi.GetCaptchaImageResult>与Promise<AxiosResponse<AuthApi.GetCaptchaImageResult>>
// let X!: Promise<AuthApi.GetCaptchaImageResult>;
// X.then((res) => {
//   console.log(res.img);
// });
// let y!: Promise<AxiosResponse<AuthApi.GetCaptchaImageResult>>;
// y.then((res) => {
//   console.log(res.data.img);
// });
export const getCaptChaImage = () =>
  baseRequestClient.get<AxiosResponse<AuthApi.GetCaptchaImageResult>>(
    'http://100.122.211.103:8080/captchaImage',
    // 'http://192.168.68.116:8080/captchaImage',
  );

// 用户注册
export const userRegister = (params: AuthApi.RegisterParams) =>
  baseRequestClient.post<AxiosResponse<AuthApi.RegisterResult>>(
    // 'http://192.168.68.116:8080/register',
    'http://100.122.211.103:8080/register',
    params,
  );

// 登录
export async function loginApi(data: AuthApi.LoginParams) {
  return requestClient.post<AuthApi.LoginResult>('/auth/login', data);
}
// 刷新
export async function refreshTokenApi() {
  return baseRequestClient.post<AuthApi.RefreshTokenResult>('/auth/refresh', {
    withCredentials: true,
  });
}
// 退出登录
export async function logoutApi() {
  return baseRequestClient.post('auth/logout', {
    withCredentials: false,
  });
}

// 获取用户权限
export async function getAccessCodesApi() {
  return requestClient.get<string[]>('/auth/codes');
}
